package com.bsj.power.system.service.impl;

import com.bsj.power.common.config.cached.RedisCached;
import com.bsj.power.common.config.global.JsonResult;
import com.bsj.power.common.config.global.JsonResultEnum;
import com.bsj.power.common.config.redis.RedisConstant;
import com.bsj.power.common.constant.NumericalConstants;
import com.bsj.power.common.util.SpringUtil;
import com.bsj.power.system.service.OpenApiService;
import com.bsj.power.system.service.ScheduledTasksService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

/**
 * @author LiJiaXin
 * @version 1.0.0
 * @description ScheduledTasksServiceImpl
 * @time 2024/8/26 19:34
 */
@Slf4j
@Service
public class ScheduledTasksServiceImpl implements ScheduledTasksService {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private RedisCached redisCached;

    @Autowired
    private OpenApiService openApiService;

    /**
     * 项目自启动，初始化定时器
     *
     * @throws SchedulerException
     */
    @PostConstruct
    public void init() throws SchedulerException {
        scheduler.clear();
//        redisCached.set(RedisConstant.WORK_SYNC_TIME, 60 * 60);
        // 启动调度器
        scheduler.start();
        // 动态添加定时任务
        String str = redisCached.get(RedisConstant.WORK_SYNC_TIME);
        if (StringUtils.isNotBlank(str)) {
            addJob(scheduler, "syncWork", "workAdd", MyScheduledTasks.class, Integer.parseInt(str));
        }
    }

    public class MyScheduledTasks implements Job {
        @Override
        public void execute(JobExecutionContext context) throws JobExecutionException {
            if (openApiService == null) {
                openApiService = SpringUtil.getBean(OpenApiService.class);
            }
            //具体的任务
            openApiService.syncSysWorkList();
        }
    }

    /**
     * 添加定时任务
     *
     * @param scheduler
     * @param jobName
     * @param groupName
     * @param jobClass
     * @param second
     * @return void
     * @author ljx
     * @time 2024/8/26 21:20
     */
    public static void addJob(Scheduler scheduler, String jobName, String groupName, Class<? extends Job> jobClass, Integer second) throws SchedulerException {
        // 定义一个任务
        JobDetail job = newJob(jobClass)
                .withIdentity(jobName, groupName)
                .build();

        // 创建触发器
        Trigger trigger = newTrigger()
                .withIdentity(jobName + "Trigger", groupName)
                .startNow()
//                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
//                .build();
                .withSchedule(simpleSchedule()
                        .withIntervalInSeconds(second)
                        .repeatForever())
                .build();

        // 将任务和触发器注册到调度器中
        scheduler.scheduleJob(job, trigger);
    }

    /**
     * 删除定时任务
     *
     * @param scheduler
     * @param jobName
     * @param groupName
     * @return void
     * @author ljx
     * @time 2024/8/26 21:22
     */
    public static void deleteJob(Scheduler scheduler, String jobName, String groupName) throws SchedulerException {
        // 删除任务和触发器
        scheduler.deleteJob(new JobKey(jobName, groupName));
    }


    /**
     * 设置工单定时任务
     *
     * @param second
     * @return com.bsj.power.common.config.global.JsonResult
     * @author ljx
     * @time 2024/8/26 19:36
     */
    @Override
    public JsonResult setJobTasks(Integer second) throws SchedulerException {
        if (second == null) {
            return JsonResult.fail();
        }
        if (second < 5 * 60) {
            return JsonResult.fail(JsonResultEnum.SMALL_TIME_INTERVAL);
        }
        //设置新的时间
        redisCached.set(RedisConstant.WORK_SYNC_TIME, second);
        //删除原先的任务
        deleteJob(scheduler, "syncWork", "workAdd");
        //创建新的任务
        addJob(scheduler, "syncWork", "workAdd", MyScheduledTasks.class, second);
        return JsonResult.success();
    }

    /**
     * 获取工单定时任务时间间隔
     *
     * @return com.bsj.power.common.config.global.JsonResult<java.lang.Integer>
     * @author ljx
     * @time 2024/8/28 10:20
     */
    @Override
    public JsonResult<Integer> getJobTasksTimeInterval() {
        String str = redisCached.get(RedisConstant.WORK_SYNC_TIME);
        if (StringUtils.isNotBlank(str)) {
            int second = Integer.parseInt(str);
            if (second > NumericalConstants.ZERO) {
                return JsonResult.success(second);
            }
        }
        return JsonResult.fail();
    }

    /**
     * 返回一个布尔值代表一个给定的Cron表达式的有效性
     *
     * @param cronExpression Cron表达式
     * @return boolean 表达式是否有效
     */
    public static boolean isValid(String cronExpression) {
        return CronExpression.isValidExpression(cronExpression);
    }

}
